package com.vshop.controller.externalInterface;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.vshop.entity.external.deviceinfo.request.RequestQueryDeviceInfo;
import com.vshop.entity.external.deviceinfo.request.RequestQueryDeviceInfoData;
import com.vshop.entity.external.deviceinfo.response.ResponseQueryDeviceInfo;
import com.vshop.entity.external.deviceinfo.response.ResponseQueryDeviceInfoData;
import com.vshop.entity.external.deviceinfo.response.ResponseQueryDeviceInfoTradeData;
import com.vshop.entity.external.deviceinfo.response.ResponseQueryDeviceInfoTradeDataPackageOrder;
import com.vshop.entity.interfacerequest.ExceptionRequest;
import com.vshop.entity.requestinterface.Constant;
import com.vshop.entity.requestinterface.usercardorder.querydevicerealtime.request.RequestQueryDeviceRealTimeNew;
import com.vshop.entity.requestinterface.usercardorder.querydevicerealtime.response.ResponseQueryDeviceRealTime;
import com.vshop.entity.requestinterface.usercardorder.querydevicerealtime.response.ResponseQueryDeviceRealTimeTradeData;
import com.vshop.entity.requestinterface.usercardorder.querydevicerealtime.response.ResponseQueryDeviceRealTimeTradeDataPackageOrder;
import com.vshop.service.PartnerInfoService;
import com.vshop.service.SequenceService;
import com.vshop.utils.HttpUtil;
import com.vshop.utils.Md5Encrypt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 查询设备实时信息
 * 接入方可以通过调用该接口，查询某个设备信息，包括设备的基本信息、设备当前订购的套餐信息等
 * <p>
 * 此接口的意义在于查询到设备如果正在使用期内：
 * 提示用户“原有订单有关闭风险”，如果用户确认，便触发关闭正在使用的订单。
 * 如果设备不是正在使用的时候不用提示
 *
 * @author lm
 * @date 2019/09/17
 */
@RestController
@Api(description = "查询设备信息 ")
@Slf4j
public class QueryDeviceController {
    @Autowired
    private SequenceService sequenceService;

    @Autowired
    private PartnerInfoService partnerInfoService;

    /**
     * 直接请求网关xml接口的地址
     */
    @Value("${iot.requestURI}")
    private String requestURI;

    @CrossOrigin
    @PostMapping(value = "queryDeviceInfo", produces = "application/json;charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "查询设备信息 ", response = ResponseQueryDeviceInfo.class)
    public String queryDeviceInfo(@ApiParam @RequestBody RequestQueryDeviceInfo request) {

        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();

        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());

        //3,定义要回复的内容
        String jsonString;

        ExceptionRequest utils = new ExceptionRequest();
        String requestStr = JSON.toJSONString(request);
        if (requestStr == null) {
            log.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            log.info("前端请求报文是：" + requestStr);
            RequestQueryDeviceInfo requestPackage = JSONArray.parseObject(requestStr, RequestQueryDeviceInfo.class);
            String requestSign = requestPackage.getSign();
            if (requestPackage.getSign() == null) {
                log.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                log.info("请求的签名是：" + requestSign);
                RequestQueryDeviceInfoData requestData = requestPackage.getData();
                if (requestData == null) {
                    log.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {

                    String ConnSeqNo = requestData.getConnSeqNo();
                    String partnerCode = requestData.getPartnerCode();
                    String secret = partnerInfoService.getSecretByPartnerCode(partnerCode);
                    String tradeTime = requestData.getTradeTime();
                    String tradeType = requestData.getTradeType();
                    String version = requestData.getVersion();

                    if (StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(partnerCode) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(tradeType) || StringUtils.isBlank(version) || requestData.getTradeData() == null) {
                        log.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {
                        String deviceCode = requestData.getTradeData().getDeviceCode();
                        if (StringUtils.isBlank(deviceCode)) {
                            log.info("请求报文不合法:tradeData参数不合法");
                            jsonString = utils.dataWeiKong(connSeqNo, curtime);
                            return jsonString;
                        } else {

                            String str = JSON.toJSONString(requestData);
                            String sign = utils.calculateSignature(str);
                            log.info("计算的签名是：" + sign);
                            if (!requestSign.equalsIgnoreCase(sign)) {
                                jsonString = utils.signatureFailure(ConnSeqNo, tradeTime, tradeType, "0001", "签名有误，请确认签名！");
                                return jsonString;

                            } else {

                                RequestQueryDeviceRealTimeNew deviceInfo = new RequestQueryDeviceRealTimeNew();
                                deviceInfo.setDeviceId(deviceCode);
                                deviceInfo.setPartnerCode(partnerCode);
                                deviceInfo.setSecret(secret);
                                //组装需要的json去请求报文
                                String requestInterface = JSON.toJSONString(deviceInfo);
                                log.info("请求报文：" + requestInterface);
                                String url = requestURI + Constant.iot_queryDeviceRealTimeNew_2;
                                // 发送post请求，并接收返回结果
                                String returnStr = HttpUtil.httpPost(url, requestInterface);
                                log.info("北京响应：" + returnStr);
                                ResponseQueryDeviceRealTime response = JSONArray.parseObject(returnStr, ResponseQueryDeviceRealTime.class);

                                if (response != null) {

                                    if (true == Constant.RET_CODE_0000.equalsIgnoreCase(response.getRetCode())) {

                                        ResponseQueryDeviceInfoTradeData tradeData = new ResponseQueryDeviceInfoTradeData();

                                        if (response.getTradeData() != null && response.getTradeData().size() >= 1) {

                                            for (ResponseQueryDeviceRealTimeTradeData tr : response.getTradeData()) {

                                                if (StringUtils.isNotBlank(tr.getLifecycle()) && tr.getPackageOrder() != null && tr.getPackageOrder().size() >= 1) {

                                                    ResponseQueryDeviceInfoTradeDataPackageOrder packageOrder = new ResponseQueryDeviceInfoTradeDataPackageOrder();

                                                    for (ResponseQueryDeviceRealTimeTradeDataPackageOrder porder : tr.getPackageOrder()) {

                                                        if (StringUtils.isNotBlank(porder.getOrderCode())) {
                                                            packageOrder.setOrderId(porder.getOrderCode());
                                                            packageOrder.setPackageCode(porder.getPackageCode());
                                                            packageOrder.setPackageName(porder.getPackageName());
                                                            packageOrder.setPackageType(porder.getPackageType());
                                                            packageOrder.setOrderPeriod(porder.getOrderPeriod());

                                                            if (StringUtils.isNotBlank(porder.getBuyType())) {
                                                                packageOrder.setBuyType(porder.getBuyType());
                                                            } else {
                                                                packageOrder.setBuyType("");
                                                            }
                                                            if (StringUtils.isNotBlank(porder.getFlow())) {
                                                                packageOrder.setFlow(porder.getFlow());
                                                            } else {
                                                                packageOrder.setFlow("");
                                                            }
                                                            if (StringUtils.isNotBlank(porder.getUsedFlow())) {
                                                                packageOrder.setUsedFlow(porder.getUsedFlow());
                                                            } else {
                                                                packageOrder.setUsedFlow("");
                                                            }
                                                            if (StringUtils.isNotBlank(porder.getFlowUseRate())) {
                                                                packageOrder.setFlowUseRate(porder.getFlowUseRate());
                                                            } else {
                                                                packageOrder.setFlowUseRate("");
                                                            }
                                                            if (StringUtils.isNotBlank(porder.getOrderUsedFlow())) {
                                                                packageOrder.setOrderUsedFlow(porder.getOrderUsedFlow());
                                                            } else {
                                                                packageOrder.setOrderUsedFlow("");
                                                            }
                                                            if (StringUtils.isNotBlank(porder.getOrderDate())) {
                                                                packageOrder.setOrderDate(porder.getOrderDate());
                                                            } else {
                                                                packageOrder.setOrderDate("");
                                                            }
                                                            if (StringUtils.isNotBlank(porder.getActiveDate())) {
                                                                packageOrder.setActiveDate(porder.getActiveDate());
                                                            } else {
                                                                packageOrder.setActiveDate("");
                                                            }
                                                            if (StringUtils.isNotBlank(porder.getExpireDate())) {
                                                                packageOrder.setExpireDate(porder.getExpireDate());
                                                            } else {
                                                                packageOrder.setExpireDate("");
                                                            }


                                                        }

                                                    }
                                                    tradeData.setDeviceCode(tr.getDeviceId());
                                                    tradeData.setOtaFlag(tr.getOtaFlag());
                                                    tradeData.setBipFlag(tr.getBipFlag());
                                                    tradeData.setMultiImsiFlag(tr.getMultiImsiFlag());
                                                    tradeData.setLifecycle(tr.getLifecycle());
                                                    tradeData.setLifecycleStartTime(tr.getLifecycleStartTime());
                                                    tradeData.setLifecycleEndTime(tr.getLifecycleEndTime());
                                                    tradeData.setLifecycleSlientPeriod(tr.getLifecycleSlientPeriod());
                                                    tradeData.setLifecycleShutdownPeriod(tr.getLifecycleShutdownPeriod());
                                                    tradeData.setPackageOrder(packageOrder);

                                                    ResponseQueryDeviceInfoData data = new ResponseQueryDeviceInfoData();
                                                    data.setConnSeqNo(ConnSeqNo);
                                                    data.setPartnerCode(partnerCode);
                                                    data.setTradeType(tradeType);
                                                    data.setTradeTime(tradeTime);
                                                    data.setRetCode(response.getRetCode());
                                                    data.setRetMsg(response.getResultInfo());
                                                    data.setTradeData(tradeData);

                                                    ResponseQueryDeviceInfo res = new ResponseQueryDeviceInfo();
                                                    res.setData(data);
                                                    res.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));
                                                    jsonString = JSON.toJSONString(res);
                                                    log.info("响应报文：" + jsonString);
                                                    return jsonString;


                                                } else {
                                                    // 设备正在使用期内，但是没有订单信息,此时异常
                                                    ResponseQueryDeviceInfoData data = new ResponseQueryDeviceInfoData();
                                                    data.setConnSeqNo(ConnSeqNo);
                                                    data.setPartnerCode(partnerCode);
                                                    data.setTradeType(tradeType);
                                                    data.setTradeTime(tradeTime);
                                                    data.setRetCode("9999");
                                                    data.setRetMsg("设备订单信息可能存在异常！");
                                                    data.setTradeData(tradeData);

                                                    ResponseQueryDeviceInfo res = new ResponseQueryDeviceInfo();
                                                    res.setData(data);
                                                    res.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));
                                                    jsonString = JSON.toJSONString(res);
                                                    log.info("响应报文：" + jsonString);
                                                    return jsonString;

                                                }


                                            }
                                        } else {

                                            ResponseQueryDeviceInfoData data = new ResponseQueryDeviceInfoData();
                                            data.setConnSeqNo(ConnSeqNo);
                                            data.setPartnerCode(partnerCode);
                                            data.setTradeType(tradeType);
                                            data.setTradeTime(tradeTime);
                                            data.setRetCode(response.getRetCode());
                                            data.setRetMsg(response.getResultInfo());
                                            data.setTradeData(tradeData);

                                            ResponseQueryDeviceInfo res = new ResponseQueryDeviceInfo();
                                            res.setData(data);
                                            res.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));
                                            jsonString = JSON.toJSONString(res);
                                            log.info("响应报文：" + jsonString);
                                            return jsonString;

                                        }


                                    } else {
                                        ResponseQueryDeviceInfoData data = new ResponseQueryDeviceInfoData();
                                        data.setConnSeqNo(ConnSeqNo);
                                        data.setPartnerCode(partnerCode);
                                        data.setTradeType(tradeType);
                                        data.setTradeTime(tradeTime);
                                        data.setRetCode(response.getRetCode());
                                        data.setRetMsg(response.getResultInfo());

                                        ResponseQueryDeviceInfo res = new ResponseQueryDeviceInfo();
                                        res.setData(data);
                                        res.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));
                                        jsonString = JSON.toJSONString(res);
                                        log.info("响应报文：" + jsonString);
                                        return jsonString;
                                    }


                                } else {
                                    ResponseQueryDeviceInfoData data = new ResponseQueryDeviceInfoData();
                                    data.setConnSeqNo(ConnSeqNo);
                                    data.setPartnerCode(partnerCode);
                                    data.setTradeType(tradeType);
                                    data.setTradeTime(tradeTime);
                                    data.setRetCode("9999");
                                    data.setRetMsg("接口响应出现异常");

                                    ResponseQueryDeviceInfo res = new ResponseQueryDeviceInfo();
                                    res.setData(data);
                                    res.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));
                                    jsonString = JSON.toJSONString(res);
                                    log.info("响应报文：" + jsonString);
                                    return jsonString;

                                }

                            }
                        }
                    }
                }
            }
        }

        return null;
    }


}
